/**
 * 
 */
package table;

import java.awt.Component;
import java.util.EventObject;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.EventListenerList;
import javax.swing.table.TableCellEditor;

/**
 * @author Ken
 *
 */
public class CheckboxEditor extends JCheckBox implements TableCellEditor{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected EventListenerList m_listenerList = new EventListenerList();
	protected ChangeEvent m_changeEvent = new ChangeEvent(this);

	@Override
	public void addCellEditorListener(CellEditorListener l) {
		m_listenerList.add(CellEditorListener.class, l);		
	}

	@Override
	public void cancelCellEditing() {
		fireEditingCanceled();		
	}

	private void fireEditingCanceled() {
		CellEditorListener listener;
        Object[] listeners = m_listenerList.getListenerList();
        for(int i=0; i< listeners.length; i++){
            if(listeners[i] == CellEditorListener.class){
                listener = (CellEditorListener) listeners[i+1];
                listener.editingCanceled(m_changeEvent);
            }
        }
	}

	@Override
	public Object getCellEditorValue() {
		return isSelected();
	}

	@Override
	public boolean isCellEditable(EventObject arg0) {
		return true;
	}

	@Override
	public void removeCellEditorListener(CellEditorListener l) {
		m_listenerList.remove(CellEditorListener.class, l);		
	}

	@Override
	public boolean shouldSelectCell(EventObject arg0) {
		return true;
	}

	@Override
	public boolean stopCellEditing() {
		fireEditingStopped();
		return true;
	}

	private void fireEditingStopped() {
		CellEditorListener listener;
        Object[] listeners = m_listenerList.getListenerList();
        for(int i=0; i<listeners.length; i++){
            if(listeners[i] == CellEditorListener.class){
                listener = (CellEditorListener) listeners[i+1];
                listener.editingStopped(m_changeEvent);
            }
        }
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, int row, int column) {
		boolean isCheck = new Boolean(value.toString());
        setSelected(isCheck);        
        return this;
	}
}
